package com.imooc.miaosha.service;

import com.imooc.miaosha.dao.OrderDao;
import com.imooc.miaosha.domian.MiaoShaOrder;
import com.imooc.miaosha.domian.OrderInfo;
import com.imooc.miaosha.domian.User;
import com.imooc.miaosha.redis.keys.OrderKey;
import com.imooc.miaosha.redis.RedisFactory;
import com.imooc.miaosha.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 模块描述: <br>
 * (订单服务)
 *
 * @Author: Mr. xyb
 * @Date: 2019/4/14 15:23
 * @since: 1.8.0
 * @version: 1.0.0
 */
@Service
public class OrderService {


    /**
     * 对象缓存，查询秒杀订单
     *
     * @param userId
     * @param goodsId
     * @return
     */
    public MiaoShaOrder getMiaoshaOrderByUserIdGoodsId(Long userId, Long goodsId) {
        MiaoShaOrder miaoShaOrder = redisFactory.get(OrderKey.getMiaoshaOrderByUidGid, "" + userId + "" + goodsId, MiaoShaOrder.class);
        if (miaoShaOrder == null) {
            miaoShaOrder = orderDao.getMiaoshaOrderByUserIdGoodsId(userId, goodsId);
        }
        return miaoShaOrder;
    }

    /**
     * 创建订单，缓存秒杀订单对象
     *
     * @param user
     * @param goodsVo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public OrderInfo createOrder(User user, GoodsVO goodsVo) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(0L);
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goodsVo.getId());
        orderInfo.setGoodsName(goodsVo.getGoodsName());
        orderInfo.setGoodsPrice(goodsVo.getGoodsPrice());
        orderInfo.setOrderChannel(1);
        orderInfo.setStatus(0);
        orderInfo.setUserId(user.getId());
        orderDao.insert(orderInfo);
        MiaoShaOrder miaoShaOrder = new MiaoShaOrder();
        miaoShaOrder.setGoodsId(goodsVo.getId());
        miaoShaOrder.setOrderId(orderInfo.getId());
        miaoShaOrder.setUserId(user.getId());
        orderDao.insertMiaoShaOrder(miaoShaOrder);
        redisFactory.set(OrderKey.getMiaoshaOrderByUidGid, "" + user.getId() + "" + goodsVo.getId(), miaoShaOrder);
        return orderInfo;
    }


    /**
     * 查询订单
     *
     * @param orderId
     * @return
     */
    public OrderInfo getOrderById(long orderId) {
        return orderDao.getOrderById(orderId);
    }


    public void deleteOrders() {
        orderDao.deleteOrders();
        orderDao.deleteMiaoshaOrders();
    }

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private RedisFactory redisFactory;


}
